﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Smo = Microsoft.SqlServer.Management.Smo;
using Common = Microsoft.SqlServer.Management.Common;

namespace BusinnesLogic.ServerObjects
{
    public class SqlServer : Server
    {
        #region Ctor

        public SqlServer(string servername, string userName, string password)
            : base(servername, userName, password)
        {
            _ServerConnection = new Common.ServerConnection(servername, userName, password);
            _Server = new Smo.Server(_ServerConnection);

            // Fill the properties
            FillProperties();
        }

        #endregion

        #region Private Properties

        private Smo.Server _Server;
        private Common.ServerConnection _ServerConnection;
        private List<SqlDatabase> _SqlDatabases;
 
        #endregion

        #region Public Methods

        public override List<Database> Databases
        {
            get
            {
                if (_Server == null || _Server.Databases == null)
                    return null;
                else
                {
                    foreach (Smo.Database database in _Server.Databases)
                    {
                        SqlDatabase sqlDataBase = new ServerObjects.SqlDatabase(database.ToString(), _Server);

                        // Add database if is not a System Database
                        if(!database.IsSystemObject)
                            _SqlDatabases.Add(sqlDataBase);
                    }

                    return _SqlDatabases.Cast<Database>().ToList();
                }

            }
        }

        public override Database this[int index]
        {
            get
            {
                Smo.Database database = _Server.Databases[index];

                if (database == null)
                    return null;
                else
                {
                    return this.Databases[index];
                }
            }
            set
            {
                Databases[index] = value;
            }
        }

        #endregion

        #region Private Methods

        private void FillProperties()
        {
            this.Name = _Server.Name;
            this.Version = _Server.VersionString;
            this.Type = ServerType.SqlServer;
            this.ConnectionString = _Server.ConnectionContext.ConnectionString;
            this._SqlDatabases = new List<SqlDatabase>();
        }
        
        #endregion
    }
}
